

package cn.yunhe.insurance.realms;


import cn.yunhe.insurance.entity.Emp;
import cn.yunhe.insurance.entity.Permission;
import cn.yunhe.insurance.entity.Role;
import cn.yunhe.insurance.service.EmpService;
import cn.yunhe.insurance.service.RoleService;
import cn.yunhe.insurance.service.impl.RoleServiceImpl;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Set;



/**
 * @author 葛森
 * <p>
 * 授权认证操作
 */

public class UserLoginRealm extends AuthorizingRealm {
    @Resource
    private EmpService empService;
    @Resource
    private RoleService roleService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        Emp emp= (Emp) principals.getPrimaryPrincipal();
        Set<String> permissionSet=new HashSet<>();
        Role role=new Role();
        role.setRuuid(emp.getRole().getRuuid());

        List<Permission> list=roleService.getRolePermission(role).getPermissionSet();



        if(!CollectionUtils.isEmpty(list)){
            for (Permission p:list) {
                permissionSet.add(p.getPname());
            }
        }
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
         info.addRole(emp.getRole().getRname());
         info.addStringPermissions(permissionSet);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //加这一步的目的是在Post请求的时候会先进认证，然后在到请求
        if (token.getPrincipal() == null) {

            return null;
        }

        String name = token.getPrincipal().toString();
        System.out.println();
        Emp emp = new Emp();
        emp.setEmpName(name);
        emp = empService.Login(emp);

        if(emp==null){
            return null;
        }else {
            AuthenticationInfo info = new SimpleAuthenticationInfo(emp, emp.getEmpPassword(), ByteSource.Util.bytes(name), getName());
            return info;
        }

    }

    public EmpService getEmpService() {
        return empService;
    }

    public void setEmpService(EmpService empService) {
        this.empService = empService;
    }

    public RoleService getRoleService() {
        return roleService;
    }

    public void setRoleService(RoleService roleService) {
        this.roleService = roleService;
    }
}


